package com.douwong.student.core;

import android.content.Context;
import android.util.Log;

import com.douwong.student.db.PrepareReaourceDBService;
import com.douwong.student.interfaces.UpdatePro;
import com.douwong.student.utils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 备课资源下载线程
 * 
 * @author leihuajie
 * 
 */
public class  ResourceLoadThread extends Thread {

	private boolean isStop = false;
    private static final String TAG="ResourceLoadThread";
	private String loadUrl;
	private String fileName;
	private UpdatePro workListener;
	private boolean load = true;
	private int fileId;
	private long getLength;
	private long totalSize;
	private Context context;
	HttpURLConnection conn;
	OutputStream output = null;
	InputStream input = null;
	int dataSize = 0;
	// 读取大文件
	byte[] buffer;

	long tempSize = 0;

	public ResourceLoadThread(String loadUrl, String fileName, int fileId, Context context) {
		this.fileName = fileName;
		this.loadUrl = loadUrl;
		this.fileId = fileId;
		this.context = context;
	}

	@Override
	public void run() {
		super.run();
		URL url;
		try {
			String fPath = FileUtils.RESOURCE_DIR + fileName;
			File file = new File(fPath);
			if (!file.exists()) {
				file.createNewFile();
			}
			// HttpClient hp=HttpClient

			url = new URL(loadUrl);

			// 读取大文件
			buffer = new byte[1024];
			tempSize = 0;
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(8000);
			conn.setReadTimeout(8000);
			if (isStop) {
				Log.d(TAG,"resume download, current size : "+getLength);
				getLength = file.length();
				totalSize = PrepareReaourceDBService.getInstance(context).queryTotalSize(fileId);
				conn.setRequestProperty("Range", "bytes=" + getLength + "-" + totalSize);
			}
			if (conn.getResponseCode() == 200) {
				input = conn.getInputStream();
				output = new FileOutputStream(file);
				long length = conn.getContentLength();
				PrepareReaourceDBService.getInstance(context).updateSize(fileId, length);
			} else if (conn.getResponseCode() == 206) {//接着上次下载
				input = conn.getInputStream();
				output = new FileOutputStream(file, true);
			} else {
				Log.e(TAG,"download will cancel,responecode erro..");
				return;
			}
			try {
				while (load) {
					int len = -1;
					if ((len = input.read(buffer)) != -1) {
						output.write(buffer, 0, len);
						//Log.i(TAG,"写入成功");
						dataSize += len;
						tempSize += len;
						if (tempSize >= 20 * 1024) {
							tempSize = 0;
							workListener.update(getLength + dataSize, fileId);
						}
					} else {
						Log.i(TAG,"downloadover savepath : "+fPath);
						workListener.loadCompleted(fileId);
						load=false;
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				try {
					if (output != null) {
						output.close();
					}
					if (input != null) {
						input.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			/*new Thread(){

				@Override
				public void run() {
					super.run();
					try {
						while (load) {
							int len = -1;
							if ((len = input.read(buffer)) != -1) {
								output.write(buffer, 0, len);
								Log.e("ResourceLoadThread","写入成功");
								dataSize += len;
								tempSize += len;
								if (tempSize >= 20 * 1024) {
									tempSize = 0;
									workListener.update(getLength + dataSize, fileId);
								}
							} else {
								Log.e("下载完了", "下载完了");
								workListener.loadCompleted(fileId);
								break;
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}finally {
						try {
							if (output != null) {
								output.close();
							}
							if (input != null) {
								input.close();
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				
			}.start();*/
			
		} catch (Exception e) {// 异常时保存当前的下载状态
			// PrepareResource pr=new PrepareResource();
			// pr.setLoading(true);
			// pr.setPause(true);
			// pr.setLoaded(false);
			// pr.setCurrentPro(dataSize);
			// pr.setId(fileId);
			// PrepareReaourceDBService.getInstance(context).upDateLoading(pr);
			// e.printStackTrace();
			e.printStackTrace();
		}
	}

	public boolean isStop() {
		return isStop;
	}

	public void setStop(boolean isStop) {
		this.isStop = isStop;
	}

	public void updateLoadPro(UpdatePro workListener) {
		this.workListener = workListener;
	}

	public boolean isLoad() {
		return load;
	}

	public void setLoad(boolean load) {
		this.load = load;
	}
}
